angular.module('app').component('winitFile', {
	templateUrl: getTemplateUrl('matrix/component/tpl/winitFile.html'),
	bindings: {
			datas : '<',
			blur  : '&',
			reqId : '<',
			fileType: '<',
			selectType: '@'
	},
	controller: function ($scope, $stateParams, $rootScope, $timeout, $http, $element, $attrs, $location, $anchorScroll, lodash){
		var ctrl = this;
		$scope.info = {
			reqId         : "",
			reqDetails    : [],
			issuesList    : [],
			flowData      : [],
			prototypeData : [],
			featureData   : [],
			remarkData    : [],
			noticeData    : "",
			manualData    : [],
			reportFormList: [],
			reqFeatulreArray: [],
			indexNum      : 0,
			fileType      : false,    //true：文档模式   false：宣讲
			fileBg        : false,
			fileIssue     : false,
			fileFlow      : false,
			fileFeature   : false,
			fileReportForm: false,
			fileManual    : false,
			fileRemark    : false,
			fileNotice    : false
		};

		//获取传入的参数
		ctrl.$onChanges = function(data) {
			$scope.info.indexNum = 0;
			switch(ctrl.selectType) {
				case "flow":
					setFileStatus("flow");
					break;
				case "feature":
					setFileStatus("feature");
					break;
				case "manual":
					setFileStatus("manual");
					break;
				case "report":
					setFileStatus("report");
					break;
				case "remark":
					setFileStatus("remark");
					break;
				case "notice":
					setFileStatus("notice");
					break;
				default:
					setFileStatus("other");
			}
			if(data && data.reqId) {
				$scope.info.reqId = data.reqId.currentValue;
				$scope.info.fileType = ctrl.fileType;
				if(ctrl.selectType == "feature") {
					getReqFeatureSignle($scope.info.reqId, $scope.info.fileType);
				}
				if(ctrl.selectType == "remark") {
					getReqRemarks($scope.info.reqId);
				}
				if(ctrl.selectType == "notice") {
					getReqNotice($scope.info.reqId);
				}
				if(ctrl.selectType == "manual") {
					getReqManual($scope.info.reqId, $scope.info.fileType);
				}
				if(ctrl.selectType == "report") {
					getReportForm($scope.info.reqId);
				}
				if($scope.info.reqId && ctrl.selectType != "feature" && ctrl.selectType != "remark" && ctrl.selectType != "notice" && ctrl.selectType != "manual" && ctrl.selectType != "report") {
					getReqFeatureSignle($scope.info.reqId, $scope.info.fileType);
					// getReqDetails($scope.info.reqId, $scope.info.fileType);
					// getIssuesByReqId($scope.info.reqId);
					// getReqFlows($scope.info.reqId, "", "", $scope.info.fileType);
					// getReqFeatures($scope.info.reqId, $scope.info.fileType);
					getReqRemarks($scope.info.reqId);
					getReqNotice($scope.info.reqId);
					getReportForm($scope.info.reqId);
					// getReqManual($scope.info.reqId, $scope.info.fileType);
				}
			}
		};

		ctrl.getPathLastName = function(path){
			alert(path)
			return path.last(path.split("/"));
		}

		function setFileStatus(fileName) {
			$scope.info.fileFeature    = fileName == "other" ? true : (fileName == "feature" ? true : false);
			$scope.info.fileFlow       = fileName == "other" ? true : (fileName == "flow"    ? true : false);
			$scope.info.fileManual     = fileName == "other" ? true : (fileName == "manual"  ? true : false);
			$scope.info.fileReportForm = fileName == "other" ? true : (fileName == "report"  ? true : false);
			$scope.info.fileRemark     = fileName == "other" ? true : (fileName == "remark"  ? true : false);
			$scope.info.fileNotice     = fileName == "other" ? true : (fileName == "notice"  ? true : false);
			$scope.info.fileBg         = fileName == "other" ? true : false;
			$scope.info.fileIssue      = fileName == "other" ? true : false;
		};

		//获取req详情数据
		function getReqDetails(reqId, fileType) {
			if(!reqId) {
				$rootScope.toasterWarningInfo("产品设计id不能为空！");
				return false;
			}
			var url = matrix_product_url +"/brdRequirement/getBrdRequirements?reqId="+ reqId;
			$http.get(url).success(function(result) {
				if(result.code == "0") {
					if(!result.data) {
						$rootScope.toasterWarningInfo("获取详情数据错误！");
						return false;
					}
					$scope.info.reqDetails = result.data[0];
					// $scope.info.reqDetails.reqDesc = lodash.trim($scope.info.reqDetails.reqDesc, "</p>");
				} else {
					$rootScope.toasterErrorInfo(result.desc);
				}
			}).then(function(response) {
				getIssuesByReqId(reqId, fileType);
			});
		};

		//根据req id获取issue数据集
		function getIssuesByReqId(reqId, fileType) {
			var url = matrix_product_url +"/issue/getReqIssues?reqId="+ reqId;
			$http.get(url).success(function(result) {
				if(result.code == "0") {
					$scope.info.issuesList = result.data;
				} else {
					$rootScope.toasterErrorInfo(result.desc);
				}
			}).then(function(response) {});
		};

		//根据req获取req最后一次提交关联的流程
		function getReqFlows(reqId, relateFlow, resItem, type) {
			var url = "";
			url = type == true ? (matrix_product_url +"/flow/getReqLatestSubmitFlows?reqId="+ reqId) : (matrix_product_url +"/flow/getReqFlows?reqId="+ reqId +"&withAttr=0");
			$http.get(url).success(function(result) {
				if(result.code == "0") {
					if(result.data) {
						if(relateFlow) {
							angular.forEach(resItem.relateFlows, function(flow) {
								var flowIndex = lodash.findIndex(result.data, function(r) {
									return r.id == flow.flowId;
								});
								if(flowIndex == -1) {
									flow.hasFlow = false;
								} else {
									flow.hasFlow = true;
								}
							});
							return resItem;
						} else {
							var flowData = [];
							angular.forEach(result.data, function(res) {
								if(res.status != "NODE_UPDATE") {
									res.flowDatas = {"nodeDataArray": (res.attrs ? (res.attrs.nodeDataArray || []) : []), "linkDataArray": (res.attrs ? (res.attrs.linkDataArray || []) : [])};
									flowData.push(res);
									getFlowRelateFeatures(reqId, res.id, res);
								}
							});

							$scope.info.flowData = flowData;
						}
					} else {
						$scope.info.flowData = null;	
					}
				} else {
					$rootScope.toasterErrorInfo(result.desc);
				}
			}).then(function(response) {
				if($stateParams.type == "view") {
					if(ctrl.selectType == "file" || ctrl.selectType == "feature") {
						$timeout(function() {
							$scope.info.fileFeature = true;
						}, 500);
					}
				} else {
					$timeout(function() {
						$scope.info.fileFeature = true;
					}, 500);
				}
				// getReqFeatures(reqId, type);
			});
		};

		//获取流程关联的功能点
		function getFlowRelateFeatures(reqId, flowId, resData) {
			var url = matrix_product_url +"/flow/getFlowFeatures?flowId="+ flowId +"&reqId="+ reqId;
			$http.get(url).success(function(result) {
				if(result.code == "0") {
					if(result.data) {
						hasRelate(reqId, result.data, resData);
					}
					resData.relateFeatures = result.data;
					return resData;
				} else {
					$rootScope.toasterErrorInfo(result.desc);
				}
			});
		};

		// 获取数据，只查询一次
		function getReqFeatureSignle(reqId, fileType) {
			var url = "";
			url = fileType == true ? (matrix_product_url +"/feature/getReqLatestSubmitFeatures?reqId="+ reqId) : (matrix_product_url +"/feature/getAllFeatureForReq?reqId="+ reqId);
			$scope.info.fileFeature = false;
			$http.get(url).success(function(result) {
				if(result.code == "0") {
					if(result.data.length > 0) {
						$scope.info.reqFeatulreArray = result.data;
						$scope.info.manualData = result.data;
					}
				} else {
					$rootScope.toasterErrorInfo(result.desc);
				}
			}).then(function(response) {
				if($stateParams.type == "view" && ctrl.selectType == "feature") {
					$scope.info.fileFeature = true;
					getReqFeatures(reqId, fileType);
				} else {
					getReqDetails(reqId, fileType);
					getReqFlows(reqId, "", "", fileType);
				}
			})		
		}

		$scope.getReqFeatures = function() {
			if($scope.info.indexNum != 1) {
				$scope.info.indexNum = 1;
				console.log("加载数据");
				if(ctrl.selectType != "feature") {
					getReqFeatures($scope.info.reqId, $scope.info.fileType);
				}
			}
		}

		//判断关联的功能点当前是否存在
		function hasRelate(reqId, resultData) {
			if($scope.info.reqFeatulreArray.length > 0) {
				angular.forEach(resultData, function(item) {
					var relateIndex = lodash.findIndex($scope.info.reqFeatulreArray, function(r) {
						return r.id == item.id;
					});
					if(relateIndex == -1) {
						item.hasRelate = false;
					} else {
						item.hasRelate = true;
					}
				});
				return resultData;
			}
		}

		//根据req获取req定板前关联的原型和功能点数据
		function getReqFeatures(reqId, type) {
			if($scope.info.reqFeatulreArray.length > 0) {
				$scope.info.prototypeData = [];
				$scope.info.featureData = [];
				angular.forEach($scope.info.reqFeatulreArray, function(res) {
					getFeatureRelateFlow(reqId, res);
				});
			}
		}

		//给功能点设置流程
		function getFeatureRelateFlow(reqId, resItem) {
			var url = matrix_product_url +"/flow/getFlowsOfFeature?reqId="+ reqId +"&featureId="+ resItem.id;
			$http.get(url).success(function(result) {
				if(result.code == "0") {
					if(result.data.length > 0) {
						angular.forEach(result.data, function(resData) {
							if(!resItem.relateFlows) {
								resItem.relateFlows = [];
							}
							if(resData.status != "NODE_UPDATE") {
								resItem.relateFlows.push({"flowId": resData.id, "flowName": resData.name});
								setHasFlow(resItem);
								// getReqFlows(reqId, true, resItem, $scope.info.fileType);
							}
						});
					}
					if(resItem.type == "PROTOTYPE") {
						resItem.path = lodash.last(resItem.path.split("/"));
					}
					resItem.type == "PROTOTYPE" ? $scope.info.prototypeData.push(resItem) : $scope.info.featureData.push(resItem);
				} else {
					$rootScope.toasterErrorInfo(result.desc);
				}
			});
		};

		function setHasFlow(resItem) {
			angular.forEach(resItem.relateFlows, function(flow) {
				var flowIndex = lodash.findIndex($scope.info.flowData, function(r) {
					return r.id == flow.flowId;
				});
				if(flowIndex == -1) {
					flow.hasFlow = false;
				} else {
					flow.hasFlow = true;
				}
			});
			return resItem;
		}

		//点击锚点定位
		$scope.setLocation = function(relate, type) {
			$location.hash(type == 'flow' ? relate.flowId : relate.id);
			$anchorScroll.yOffset = 100;
			$anchorScroll();
		};

		//获取上线要求数据
		function getReqRemarks(reqId) {
			var url = matrix_product_url +"/reqRemark/getReqRemarks?reqId="+ reqId;
			$http.get(url).success(function(result) {
				if(result.code == "0") {
					angular.forEach(result.data, function(res) {
						if(res.type != null) {
							var typeItem = lodash.findWhere(config_remark_type, {key: res.type});
							res.typeName = typeItem.value;
						} else {
							res.typeName = "未定义";
						}
					});
					$scope.info.remarkData = result.data;
				} else {
					$rootScope.toasterErrorInfo(result.desc);
				}
			});
		};

		//获取上线公告
		function getReqNotice(reqId) {
			var url = matrix_product_url +"/brdRequirement/getReqNotices?reqId="+ reqId;
			$http.get(url).success(function(result) {
				if(result.code == "0") {
					$scope.info.noticeData = result.data[0];
				} else {
					$rootScope.toasterErrorInfo(result.desc);
				}
			});
		};
		// 获取报表附件
		function getReportForm(reqId) {
			var url = matrix_product_url +"/brdRequirement/getReqReportFormList?reqId="+ reqId;
			$http.get(url).success(function(result) {
				if(result.code == "0") {
					$scope.info.reportFormList = result.data;
				} else {
					$rootScope.toasterErrorInfo(result.desc);
				}
			});
		};

		//下载附件
		$scope.downloadFile=function(fileId){
			window.location.href =matrix_product_url+"/brdRequirement/getReqReportFormFile?fileId="+fileId;
		}

		$scope.openUrl=function(manual){
			if(manual.attr.url){
				window.open(manual.attr.url);
				return;
			}
		}

		// 获取用户手册变更数据
		function getReqManual(reqId, type) {
			var url = type == true ? (matrix_product_url +"/feature/getReqLatestSubmitFeatures?reqId="+ reqId) : (matrix_product_url +"/feature/getAllFeatureForReq?reqId="+ reqId +"&withAttr=1");
			$http.get(url).success(function(result) {
				if(result.code == "0") {
					$scope.info.manualData = result.data;
				} else {
					$rootScope.toasterErrorInfo("获取用户手册数据错误！");
				}
			});
		}

		// 全屏
        $scope.requestFullScreen = function () {
			var element = document.getElementById("fileContent");
			$("#fileContent").css("width", "100%");
			$("#fileContent").css("height", "100%");
			$("#fileContent").css("overflow", "scroll");
			$scope.isFullScreen = true;
            var requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen;
            if (requestMethod) {
                requestMethod.call(element);
            } else if (typeof window.ActiveXObject !== "undefined") {
                var wscript = new ActiveXObject("WScript.Shell");
                if (wscript !== null) {
					wscript.SendKeys("{F11}");
                }
            }
        }

		// 退出全屏
        $scope.exitFullscreen = function () {
			var de = document;
			$scope.isFullScreen = false;
            if (de.exitFullscreen) {
                de.exitFullscreen();
            } else if (de.mozCancelFullScreen) {
                de.mozCancelFullScreen();
            } else if (de.webkitCancelFullScreen) {
                de.webkitCancelFullScreen();
            }
		};
		
        document.addEventListener("mozfullscreenchange", function (e) {
            setStyle(e.currentTarget.mozFullScreen);
		});
		
        document.addEventListener("webkitfullscreenchange", function (e) {
            setStyle(e.currentTarget.webkitIsFullScreen);
		});
		
        document.addEventListener("msfullscreenchange", function (e) {
            console.log("msfullscreenchange", e);
        });

        function setStyle(type) {
            if (type == false) {
                $scope.exitFullscreen();
            }
        };
	}
});


